/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */

package UTILITARIOS;

import java.awt.Dimension;
import java.awt.FlowLayout;
import java.awt.Font;
import java.awt.event.FocusListener;
import java.awt.event.KeyAdapter;
import java.beans.PropertyChangeListener;
import java.text.SimpleDateFormat;
import java.util.Date;
import com.toedter.calendar.JDateChooser;
import java.awt.event.FocusEvent;
import java.awt.event.KeyEvent;
import javax.swing.*;
import javax.swing.event.ChangeEvent;
import javax.swing.event.ChangeListener;

/**
 *
 * @author Administrador
 */
public class PanelPickFechas extends JPanel{

    private DateCalendarPanel pnlCalendar;
	/**
	 * Etiqueta para desplegar lo que la fecha representa
	 */
	private JLabel lblDate;
	/**
	 * El calendario
	 */
	//private DateField txtDate;
	/**
	 * Campo para el dia del mes
	 */
	//private TextFieldInt txtDay;
	/**
	 * Campo para el mes del año
	 */
	//private TextFieldInt txtMonth;
	/**
	 * Campo para el año
	 */
	//private TextFieldInt txtYear;
	/**
	 * Cadena que contiene lo que la fecha representa
	 */
	private String dateLabel;
	/**
	 * Alineación que acomoda el label "fecha" en la misma alineación
	 * que los textos de la fecha
	 */
	public  static final int HORIZONTAL_ALIGNMENT = 1;
	/**
	 * Alineación que acomoda el label "fecha" en la distinta alineación
	 * que los textos de la fecha. En filas diferentes
	 */
	public static final int VERTICAL_ALIGNMENT = 2;

	private int LABEL_ALIGNMENT = HORIZONTAL_ALIGNMENT;

	public PanelPickFechas(){
		this("");
	}

	public PanelPickFechas(String dateLabel){
		this.dateLabel = dateLabel;
		setProperties();
		buildComponents();
		setPropertiesComponents();
		recoverCurrentDate();

		addComponents();

		addEvents();
	}
	public PanelPickFechas(String dateLabel, int alignment){
		LABEL_ALIGNMENT = alignment;
		this.dateLabel = dateLabel;
		setProperties();
		buildComponents();
		setPropertiesComponents();
		recoverCurrentDate();

		addComponents();

		addEvents();
	}
	/**
	 * Añade los eventos
	 *
	 */
	private void addEvents() {
		/*ChangeDateEvent cde = new ChangeDateEvent();
		txtDate.addChangeListener( cde );

		//	Evento de cambio de foco a los campos de texto
		FocusGained fge = new FocusGained();
		txtDay.addFocusListener(fge);
		txtMonth.addFocusListener(fge);
		txtYear.addFocusListener(fge);

		//	Evento de actualización de los campos/calendario
		ChangeText cte = new ChangeText();
		txtDay.addKeyListener(cte);
		txtMonth.addKeyListener(cte);
		txtYear.addKeyListener(cte);*/
	}
	/**
	 * Oyente de cambio de estado en el calendario
	 *
	 */
	class ChangeDateEvent implements ChangeListener{
		public void stateChanged(ChangeEvent e) {
			/*if( e.getSource().equals(txtDate) ){
				recoverCurrentDate();
			}*/
		}
	}
	/**
	 * Establece los campos de texto, de acuerdo a la selección
	 * del calendario
	 *
	 */
	private void recoverCurrentDate(){
		/*Date date = (Date)txtDate.getValue();

		if( !txtDay.isFocusOwner() )
			txtDay.setText(date.getDate()<10?"0"+date.getDate():""+date.getDate());

		if(!txtMonth.isFocusOwner())
			txtMonth.setText(date.getMonth()<9?"0"+(date.getMonth()+1):""+(date.getMonth()+1));

		if(!txtYear.isFocusOwner())
			txtYear.setValue(date.getYear()+1900);*/
	}
	/**
	 * Oyente de foco
	 *
	 */
	class FocusGained implements FocusListener{
		public void focusGained(FocusEvent e) {
			if(e.getSource() instanceof TexFieldInt)
				((TexFieldInt)e.getSource()).selectAll();
		}

		public void focusLost(FocusEvent e) {
			/*Date date = (Date)txtDate.getValue();
			txtDay.setText(date.getDate()<10?"0"+date.getDate():""+date.getDate());
			txtMonth.setText(date.getMonth()<9?"0"+(date.getMonth()+1):""+(date.getMonth()+1));
			txtYear.setValue(date.getYear()+1900);*/
		}

	}
	/**
	 * Oyente de cambio de texto en los campos de la fecha
	 *
	 */
	class ChangeText extends KeyAdapter {
		int textPosition = 0;

		public void keyReleased(KeyEvent e) {
			setCalendarDate();
			if( Character.isDigit(e.getKeyChar()) )
			{
				/*if( txtDay.isFocusOwner() && txtDay.getText().length() == 2 && textPosition==0 )
					txtMonth.grabFocus();
				else if( txtMonth.isFocusOwner() && txtMonth.getText().length() == 2 && textPosition==1)
					txtYear.grabFocus();*/
			}
		}

		public void keyPressed(KeyEvent e) {
			/*if( txtDay.isFocusOwner())
				textPosition = 0;
			else if( txtMonth.isFocusOwner())
				textPosition = 1;*/
		}
	}
	/**
	 * Establece en el calendario la fecha ingresada en los campos
	 *
	 */
	private void setCalendarDate(){
		/*int day = txtDay.getValue();
		int month = txtMonth.getValue();
		int year = txtYear.getValue();

		if( day>0 && month>0 && year>0 )
			txtDate.setValue( new Date(year-1900,month-1,day) );*/

	}

	private void setProperties() {
		if(LABEL_ALIGNMENT == HORIZONTAL_ALIGNMENT)
			setLayout(new FlowLayout(FlowLayout.CENTER,2,1));
		else
			setLayout(new FlowLayout(FlowLayout.LEFT,2,1));
	}

	private void buildComponents() {
		if(LABEL_ALIGNMENT == HORIZONTAL_ALIGNMENT)
			lblDate = new JLabel(dateLabel, JLabel.RIGHT);
		else
			lblDate = new JLabel(dateLabel, JLabel.LEFT);

		/*txtDate = CalendarFactory.createDateField();
		txtDate.setPrintMoon(true);
		txtDate.setShowOkCancel(true);
		txtDate.setShowToday(true);

		txtDay = new TextFieldInt(31);
		txtMonth = new TextFieldInt(12);
		txtYear = new TextFieldInt(2010);*/

                pnlCalendar = new DateCalendarPanel();
	}

	private void setPropertiesComponents() {
		Dimension dimensionLabel;
		if(LABEL_ALIGNMENT == HORIZONTAL_ALIGNMENT)
			dimensionLabel = new Dimension(dateLabel.length()*7,18);
		else
			dimensionLabel = new Dimension(dateLabel.length()*100,18);

		Font font = new Font("Tahoma",Font.PLAIN,11);

		lblDate.setPreferredSize(dimensionLabel);

		/*txtDate.setPreferredSize(new Dimension(18,20));
		txtDate.setFocusable(false);

		txtDay.setPreferredSize( new Dimension(25,20) );
		txtMonth.setPreferredSize( new Dimension(25,20) );
		txtYear.setPreferredSize( new Dimension(40,20) );

		txtDate.setFont(font);*/
                lblDate.setFont(font);

                pnlCalendar.setFont(font);
                pnlCalendar.setPreferredSize(new Dimension(100, 20));

	}

	private void addComponents() {
		add(lblDate);
		add(pnlCalendar);
	}

	public void setDate(String date){
		//txtDate.setValue( ScorpioUtil.ensureDateFormat(date) );
            SimpleDateFormat formatter = new SimpleDateFormat("dd-MM-yyyy");
            try {
                pnlCalendar.setDate(formatter.parse(date));
            } catch (Exception e) {
            }
	}

	private Date getDate(){
		Date init = (Date)pnlCalendar.getDate();
		return init;
	}

	/**
	 * This method returns date as postgres date format
	 * @return String
	 */
	private String getDateFormatted(){
		//Date init = (Date)txtDate.getValue();
		//return (init.getDate()<10?"0"+init.getDate():init.getDate())+"-"+(init.getMonth()<9?"0"+(init.getMonth()+1):(init.getMonth()+1))+"-"+(init.getYear()+1900);
            return new java.sql.Date(pnlCalendar.getDate().getTime()).toString();
	}

	public String getDateText(){
		//return txtDay.getText()+"/"+txtMonth.getText()+"/"+txtYear.getText();
		return new java.sql.Date(pnlCalendar.getDate().getTime()).toString().replace('-', '/');
	}

	public String getDateTextDB(){
		return getDateFormatted();
	}

	public static void main(String[] args) {
		PanelPickFechas panel = new PanelPickFechas("Fecha del pedido");

		JFrame frame = new JFrame();
		frame.add(panel);
		frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
		frame.setSize(300, 200);
		frame.setVisible(true);
		System.out.println(panel.getDateTextDB());

	}
	/**
	 * Limpia los campos de la fecha
	 *
	 */
	public void clear() {
            pnlCalendar.cleanup();
	}

	@Override
	public void setEnabled(boolean enabled) {
            pnlCalendar.setEnabled(enabled);
	}

	public void setMandatory( boolean flag ){
		/*txtDay.setMandatory(flag);
		txtMonth.setMandatory(flag);
		txtYear.setMandatory(flag);*/

	}

	public void addChangeDateListener(PropertyChangeListener listener){
		pnlCalendar.addPropertyChangeListener(listener);
	}

	public boolean isDateSelected(){
		return pnlCalendar.isDateSelected();
	}

	class DateCalendarPanel extends JDateChooser{

		private static final long serialVersionUID = 1L;

		public DateCalendarPanel(){
	        super(new Date());

	        /*this.getDateEditor().addPropertyChangeListener(new PropertyChangeListener() {
				@Override
				public void propertyChange(PropertyChangeEvent pe) {
					if(pe.getPropertyName().equals("date") && dateSelected){

						System.out.println("+++++++++++++++" + pe.getPropertyName());
					}
				}
			});*/
	    }

	    public java.sql.Date getSqlDate(){
	        return new java.sql.Date(getDate().getTime());
	    }

	    public String getDateStringDB(){
	        return new java.sql.Date(getDate().getTime()).toString();
	    }

	    public boolean isDateSelected(){
	    	return dateSelected;
	    }
	}


}
